package com.cyj.springbootservice.controller.lock;


import com.baomidou.mybatisplus.extension.api.R;
import com.cyj.springbootservice.service.RedisLockService;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.klock.annotation.Klock;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @description:
 * @Author C_Y_J
 * @create 2022/5/6 14:20
 **/
@Slf4j
@RestController
@AllArgsConstructor
public class RedisLockController {

    private RedisLockService redisLockService;

    @GetMapping("/redis/lock")
    public R<String> redisLock(@RequestParam(value = "userName") String userName) {
        log.info("{}进入redisLock方法", userName);
        return R.ok(redisLockService.list(userName));
    }


    @GetMapping("/invalid/redis/lock")
    public void invalidRedisLock(@RequestParam(value = "userName") String userName) {
        log.info("{}进入invalidRedisLock方法", userName);
        list(userName);
    }

    /**
     * 这种写法是不会生效的， list(userName) 相当于this.list(userName) 。
     * 走的是RedisLockController里面的list方法，而想要redis分布式锁生效的方法就是走代理对象
     *
     * @param userName
     */
    @Klock
    @SneakyThrows
    public void list(String userName) {
        log.info("{}进入list方法，成功获取锁", userName);

        Thread.sleep(3 * 1000);

        log.info("{}执行完毕list方法，成功释放锁", userName);
    }
}
